package com.hbsd.paopaobackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbsd.paopaobackend.common.ErrorCode;
import com.hbsd.paopaobackend.exception.BusinessException;
import com.hbsd.paopaobackend.mapper.BlogMapper;
import com.hbsd.paopaobackend.model.domain.Blog;
import com.hbsd.paopaobackend.model.domain.Team;
import com.hbsd.paopaobackend.model.domain.User;
import com.hbsd.paopaobackend.model.request.Blog.AddBlogRequest;
import com.hbsd.paopaobackend.model.request.Blog.BlogListRequest;
import com.hbsd.paopaobackend.model.request.Blog.SelectBlogRequest;
import com.hbsd.paopaobackend.model.vo.Blog.BlogListVO;
import com.hbsd.paopaobackend.model.vo.Blog.SelectBlogVO;
import com.hbsd.paopaobackend.model.vo.UserVO;
import com.hbsd.paopaobackend.service.BlogService;
import com.hbsd.paopaobackend.service.TeamService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zzh
 * @description 针对表【blog(博客表)】的数据库操作Service实现

 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog>
        implements BlogService {

    @Resource
    private TeamService teamService;

    /**
     * 新增博客
     *
     * @param addBlogRequest
     * @param loginUser
     * @return
     */
    @Override
    public Boolean addBlog(AddBlogRequest addBlogRequest, User loginUser) {
        if (addBlogRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        String title = addBlogRequest.getTitle();
        String content = addBlogRequest.getContent();
        Long teamId = addBlogRequest.getTeamId();
        if (teamId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "团队ID不能为空");
        }

        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.eq("id", teamId);

        Team team = teamService.getOne(teamQueryWrapper);
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }


        if (title == null || title.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题不能为空");
        }
        if (content == null || content.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容不能为空");
        }
        Blog blog = new Blog();
        try {
            BeanUtils.copyProperties(blog, addBlogRequest);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数转换失败");
        }

        Long id = loginUser.getId();
        blog.setAuthorId(id);
        boolean save = this.save(blog);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加博客失败");
        }
        return save;

    }


    /**
     * 分页查询博客列表
     *
     * @param blogListRequest
     * @param loginUser
     * @return
     */
    @Override
    public Page<BlogListVO> listBlogByPage(BlogListRequest blogListRequest, User loginUser) {
        if (blogListRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "博客列表请求参数为空");
        }
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        Long pageNum = blogListRequest.getPageNum();
        Long pageSize = blogListRequest.getPageSize();

        // 获取队伍ID
        Long teamId = blogListRequest.getTeamId();
        Long id = loginUser.getId();
        if (teamId == null || teamId <= 0 || id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }

        // 分页查询
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teamId", teamId);
        Page<Blog> page = new Page<>(pageNum, pageSize);
        Page<Blog> page1 = this.page(page, queryWrapper);

        List<BlogListVO> blogListVOList = page1.getRecords().stream().map(blog -> {
            BlogListVO blogListPage = new BlogListVO();

            try {
                BeanUtils.copyProperties(blogListPage, blog);
            } catch (Exception e) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数转换失败");
            }

            return blogListPage;
        }).collect(Collectors.toList());

        Page<BlogListVO> blogListVOPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        blogListVOPage.setRecords(blogListVOList);

        return blogListVOPage;


    }

    /**
     * 根据ID查询博客详情
     *
     * @param selectBlogRequest
     * @param loginUser
     * @return
     */
    @Override
    public SelectBlogVO getBlogById(SelectBlogRequest selectBlogRequest, User loginUser) {
        if (selectBlogRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询博客请求参数为空");
        }
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        Long id = loginUser.getId();
        if(id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }

        Long blogId = selectBlogRequest.getBlogId();
        if (blogId == null || blogId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "博客不存在");
        }

        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", blogId);
        Blog blog = this.getOne(queryWrapper);
        if(blog == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "博客不存在");
        }

        SelectBlogVO selectBlogVO = new SelectBlogVO();
        try {
            BeanUtils.copyProperties(selectBlogVO, blog);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数转换失败");
        }

        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(loginUser, userVO, "tags");
        userVO.setTags(Objects.nonNull(loginUser.getTags()) ? JSONUtil.parseArray(loginUser.getTags()).toList(String.class) : new ArrayList<>());

        selectBlogVO.setUserVO(userVO);

        return selectBlogVO;

    }

}




